﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace Generator.Helpers
{
    /// <summary>
    /// Cette classe permet d'effectuer les remplacements dans les fichiers par les paramétrages de VSTemplate
    /// http://msdn.microsoft.com/en-us/library/eehb4faa.aspx
    /// </summary>
    internal class TextReplaceHelper
    {
        public const string ORIGINAL_COMPANY_NAME = "CPN";
        public const string ORIGINAL_PROJECT_NAME = "PJN";
        public const string ORIGINAL_NAMESPACE = ORIGINAL_COMPANY_NAME + "." + ORIGINAL_PROJECT_NAME;

        public const string VERSION = "$clrversion$";
        public const string GUID = "$guid{0}$";
        public const string ITEM_NAME = "$itemname$";
        public const string MACHINE_NAME = "$machinename$";
        public const string PROJECT_NAME = "$projectname$";
        public const string REGISTERED_ORGANIZATION = "$registeredorganization$";
        public const string ROOT_NAMESPACE = "$rootnamespace$";
        public const string SAFE_ITEM_NAME = "$safeitemname$";
        public const string SAFE_PROJECT_NAME = "$safeprojectname$";
        public const string TIME = "$time$";
        public const string USER_DOMAINE = "$userdomain$";
        public const string USER_NAME = "$username$";
        public const string WEB_NAMESAPCE = "$webnamespace$";
        public const string YEAR = "$year$";

        public const string COMPANY_NAME = "$companyname$";
        public const string PROJECT_SHORT_NAME = "$projectshortname$";

        public string ReplaceNamespace(string text)
        {
            return text.Replace(ORIGINAL_NAMESPACE, PROJECT_NAME);
        }

        public XDocument ContenctReplaceParse(XDocument document)
        {
            var content = document.ToString();
            return XDocument.Parse(content);
        }

        public void ReplaceFile(string filename, params Func<string, string>[] modificationActions)
        {
            FileHelper helper = new FileHelper();
            if (helper.CheckFilenameExtension(filename))
            {
                var content = File.ReadAllText(filename);
                foreach (var action in modificationActions)
                {
                    content = action.Invoke(content);
                }
                FileHelper.RemoveReadOnlyAttribute(filename);
                File.WriteAllText(filename, content);
            }
        }


    }
}
